﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Models;
using Utilities;
using Telerik.Web.Mvc;
using Telerik.Web.Mvc.UI;

namespace Grant_Warehouse.Controllers
{ 
    public class AreaController : Controller
    {
        [GridAction]
        public ActionResult AjaxAreaIndex()
        {
            return View(CT.GetViewModel<Area>());
        }

        [GridAction]
        public ActionResult AjaxWarehouseIndex(int areaID)
        {
            return View(CT.GetViewModel<Warehouse>(w => w.AreaID == areaID));
        }

        [GridAction]
        public ActionResult AjaxStockIndex(int warehouseID)
        {
            return View(CT.GetViewModel<Stock, StockView>(s => s.WarehouseID == warehouseID,"Area","Warehouse","Category","quality"));
        }
 
        public ViewResult Index()
        {
            return View(CH.GetAllData<Area>());
        }

        public ViewResult Details(int id)
        {
            Area area = CH.GetDataById<Area>(id);
            return View(area);
        }

        public ActionResult Create()
        {
            return View();
        } 

        [HttpPost]
        public ActionResult Create(Area area)
        {
            if (ModelState.IsValid)
            {
                CH.Create<Area>(area);
                return RedirectToAction("Index");  
            }

            return View(area);
        }
 
        public ActionResult Edit(int id)
        {
            Area area = CH.GetDataById<Area>(id);
            return View(area);
        }

        [HttpPost]
        public ActionResult Edit(Area area)
        {
            if (ModelState.IsValid)
            {
                CH.Edit<Area>(area);
                return RedirectToAction("Index");
            }
            return View(area);
        }

 
        public ActionResult Delete(int id)
        {
            Area area = CH.GetDataById<Area>(id);
            return View(area);
        }


        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            try
            {
                CH.Delete<Area>(id);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "此数据被其他数据引用，为保证数据完整性，请先移除对此数据的引用，再进行删除");
                Log.LogError(ex, this);
                return View(CH.GetDataById<Area>(id));
            }

            return RedirectToAction("Index");
        }

    }
}